package com.zmj.sy.mom.srv.aps.service;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.fasterxml.jackson.dataformat.xml.ser.ToXmlGenerator;
import com.zmj.sy.mom.srv.aps.bean.dto.wms.MesPicking;
import com.zmj.sy.mom.srv.aps.bean.dto.wms.WmsPartOutboundReqDto;
import com.zmj.sy.mom.srv.aps.bean.dto.wms.WmsPartProcurementReqDto;
import com.zmj.sy.mom.srv.aps.bean.entity.aps.ApsAccessoryPick;
import com.zmj.sy.mom.srv.aps.bean.entity.base.BaseEntity;
import com.zmj.sy.mom.srv.aps.bean.entity.order.*;
import com.zmj.sy.mom.srv.aps.bean.entity.resource.LogApi;
import com.zmj.sy.mom.srv.aps.bean.vo.base.BaseIdReqVo;
import com.zmj.sy.mom.srv.aps.bean.vo.base.Result;
import com.zmj.sy.mom.srv.aps.bean.vo.powder.PowderOutNoticeApsReqVo;
import com.zmj.sy.mom.srv.aps.bean.vo.powder.PowderOutReceiveApsReqVo;
import com.zmj.sy.mom.srv.aps.bean.vo.solid.MesResponse;
import com.zmj.sy.mom.srv.aps.bean.vo.solid.MesXmlResult;
import com.zmj.sy.mom.srv.aps.bean.vo.solid.PickingItemReq;
import com.zmj.sy.mom.srv.aps.feign.WmsApiClient;
import com.zmj.sy.mom.srv.aps.feign.WmsBjkApiClient;
import com.zmj.sy.mom.srv.aps.feign.WmsLtkApiClient;
import com.zmj.sy.mom.srv.aps.mapper.*;
import com.zmj.sy.mom.srv.aps.utils.*;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@RequiredArgsConstructor
@Service
@Slf4j
public class WmsService {


    private final ApsWorkOrderMapper apsWorkOrderMapper;
    private final OrderMapper orderMapper;
    private final OrderBomMapper orderBomMapper;
    private final LogApiUtils logApiUtils;
    private final WmsApiClient wmsApiClient;
    private final PartUtilService partUtilService;
    private final PartLogMapper partLogMapper;
    private final LogApiMapper logApiMapper;
    private final SerialCodeUtils serialCodeUtils;
    private final ApsOrderMapper apsOrderMapper;
    private final WmsLtkApiClient wmsLtkApiClient;
    private final OrderAccessoriesMapper orderAccessoriesMapper;
    private final WmsBjkApiClient wmsBjkApiClient;
    private final ApsAccessoryPickMapper apsAccessoryPickMapper;

    @Transactional
    public void partProcurement(Integer id) {
//                String url = "/sional/wgMaterialPick";
//        LogApi logApi = logApiUtils.getSendLog("mom-srv-sf-pda", "外购件采购计划", url);
//        logApiUtils.setReq(logApi, wmsReqDto);
//        log.info("PDA-托盘清空-请求：" + JsonUtils.toJsonString(wmsReqDto));
//
//
//        try {
//            Map<String, Object> responseMap = restTemplate.postForObject("http://mom-srv-sf-pda" + url, wmsReqDto, Map.class);

        LogApi one = logApiMapper.lambdaQuery()
                .eq(LogApi::getSender, "mom-srv-aps")
                .eq(LogApi::getDir, 1)
                .eq(LogApi::getReceiver, "mom-srv-sf-pda")
                .eq(LogApi::getSuccess, true)
                .eq(LogApi::getUrl, "/sional/wgMaterialPick")
                .eq(LogApi::getQueryParam, id.toString())
                .last("limit 1")
                .one();

        if (one != null) {
            return ;
//            throw SyExceptionUtils.e("外购件已推送！");
        }

        List<ApsWorkOrder> list = apsWorkOrderMapper.lambdaQuery()
                .eq(ApsWorkOrder::getOrderId, id)
                .eq(ApsWorkOrder::getWorkChain, "WL")
                .orderByAsc(ApsWorkOrder::getApsOrderId)
                .orderByAsc(ApsWorkOrder::getPlanEndDateTime)
                .orderByDesc(ApsWorkOrder::getLevel)
                .list();

        if(CollUtil.isEmpty(list)){
            return;
        }

        List<Integer> orderIds = list.stream().map(ApsWorkOrder::getOrderId).distinct().collect(Collectors.toList());
        Map<Integer, Order> map = orderMapper.selectBatchIds(orderIds).stream().collect(Collectors.toMap(BaseEntity::getId, Function.identity()));


//        Map<String, ApsWorkOrder> apsWorkOrderMap = list.stream().collect(Collectors.toMap(ApsWorkOrder::getPlmId, Function.identity(), (e1, e2) -> {
//            e1.setOrderCount(e1.getOrderCount().add(e2.getOrderCount()));
//            if(e2.getPlanStartDateTime().isBefore(e1.getPlanStartDateTime())){
//                e1.setPlanStartDateTime(e2.getPlanStartDateTime());
//            }
//            return e1;
//        }));

        List<OrderBom> orderBomList  = orderBomMapper.lambdaQuery()
                .eq(OrderBom::getOrderId, id)
                .list();

//        Map<Integer, List<ApsWorkOrder>> apsOrderMap = list.stream().collect(Collectors.groupingBy(ApsWorkOrder::getApsOrderId, Collectors.toList()));

//        for (Integer apsOrderId : apsOrderMap.keySet().stream().sorted().collect(Collectors.toList())) {
//            List<ApsWorkOrder> apsWorkOrders = apsOrderMap.get(apsOrderId);
//            String pickListNo = serialCodeUtils.pickWailing();
//            for (ApsWorkOrder apsWorkOrder : apsWorkOrders) {
//
//            }
//        }

        List<Integer> apsOrderIdList = list.stream().map(ApsWorkOrder::getApsOrderId).distinct().collect(Collectors.toList());
        Collections.sort(apsOrderIdList);
        Map<Integer, List<ApsWorkOrder>> apsOrderMap = list.stream().collect(Collectors.groupingBy(ApsWorkOrder::getApsOrderId, Collectors.toList()));

        Map<Integer, String> params = new HashMap<>();
        for (Integer apsOrderId : apsOrderIdList) {
            params.put(apsOrderId, serialCodeUtils.pickWailing());
            List<ApsWorkOrder> apsWorkOrders = apsOrderMap.get(apsOrderId);
            for (int i = 0; i < apsWorkOrders.size(); i++) {
                ApsWorkOrder apsWorkOrder = apsWorkOrders.get(i);
                apsWorkOrder.setPickSeq(i + 1);
                apsWorkOrder.setPickCode(params.get(apsOrderId));
                apsWorkOrderMapper.lambdaUpdate()
                        .eq(ApsWorkOrder::getId, apsWorkOrder.getId())
                        .set(ApsWorkOrder::getPickCode, apsWorkOrder.getPickCode())
                        .set(ApsWorkOrder::getPickSeq, apsWorkOrder.getPickSeq())
                        .update();
            }
        }

        List<ApsOrder> apsOrders = apsOrderMapper.selectBatchIds(apsOrderIdList);
        Map<Integer, ApsOrder> apsOrderMap1 = apsOrders.stream().collect(Collectors.toMap(BaseEntity::getId, Function.identity()));
        Map<Integer, OrderBom> orderBomMap = orderBomList.stream().collect(Collectors.toMap(BaseEntity::getId, Function.identity()));

        List<WmsPartProcurementReqDto> wmsReqDto = list
                .stream()
                .filter(e-> StringUtils.hasText(e.getPlmId()))
                .map(e -> {
                    // 物料类型
                    WmsPartProcurementReqDto w = new WmsPartProcurementReqDto();
                    w.setPickListNo(e.getPickCode());
                    w.setPickListItemNo(e.getPickSeq());
                    w.setMaterialCode(e.getPlmId());
                    w.setGrade(e.getStandards());
                    w.setMaterial(e.getTexture());
                    w.setItemNo(e.getErpCode());
                    w.setItemName(e.getMaterName());
                    w.setQty(e.getOrderCount().intValue());
                    w.setPlanPickTime(e.getPlanStartDateTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                    w.setTimeStamp(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                    w.setNextWorkPlace(e.getWorkChain());
                    w.setConstructOrderNo(e.getWorkOrderCode());

                    if (e.getBomPid() != null){
                        OrderBom orderBom = orderBomMap.get(e.getBomPid());
                        w.setRootPlmid(orderBom.getPlmId());
                        w.setRootName(orderBom.getMaterName());
                    }

                    w.setWpxNo(PkgUtils.gen(apsOrderMap1.get(e.getApsOrderId()).getSeq()));

                    Order order = map.get(e.getOrderId());
                    w.setConstructNo(order.getConstructNo());
                    e.setPickCode(w.getPickListNo());


                    return w;
                })
                .collect(Collectors.toList());

        wmsApiClient.partProcurement(wmsReqDto,id);

//        for (WmsPartProcurementReqDto wmsPartProcurementReqDto : wmsReqDto) {
//            partUtilService.addPartWl(wmsPartProcurementReqDto.getMaterialCode(), wmsPartProcurementReqDto.getQty());
//
//            //添加零件日志
//            PartLog partLog = new PartLog();
//            partLog.setOperationType(1);
//            partLog.setPartType(3);
//            partLog.setPartId(wmsPartProcurementReqDto.getMaterialCode());
//            partLog.setPhaseCode(WL_PHASE_CODE);
//            partLog.setNextPhaseCode(WorkshopProp.KJ_PHASE_CODE);
//            partLog.setReportId(null);
//            partLog.setTotalCount(wmsPartProcurementReqDto.getQty());
//            partLog.setSuccessCount(wmsPartProcurementReqDto.getQty());
//            partLog.setErrorCount(0);
//            partLog.setAfterCount(wmsPartProcurementReqDto.getQty());
//            partLogMapper.insert(partLog);
//
//        }

//        List<WmsPartOutboundReqDto> collect = wmsReqDto.stream().map(e -> {
//            WmsPartOutboundReqDto w = new WmsPartOutboundReqDto();
//            w.setPickListItemNo(e.getPickListItemNo());
//            w.setMaterialCode(e.getMaterialCode());
//            w.setQty(e.getQty());
//            return w;
//        }).collect(Collectors.toList());

//        partOutbound(collect);

    }

    @Transactional
    public void partProcurement(Integer id, Integer coverFlag) {

        /*LogApi one = logApiMapper.lambdaQuery()
                .eq(LogApi::getSender, "mom-srv-aps")
                .eq(LogApi::getDir, 1)
                .eq(LogApi::getReceiver, "mom-sy-solid-wms")
                .eq(LogApi::getSuccess, true)
                .eq(LogApi::getUrl, "/mesApply/pickingApplyInAps")
                .eq(LogApi::getQueryParam, id.toString())
                .last("limit 1")
                .one();

        if (one != null) {
            return ;
        }*/

        LambdaQueryWrapper<ApsWorkOrder> qw = new LambdaQueryWrapper<>();
        qw.eq(ApsWorkOrder::getOrderId, id);
        qw.eq(ApsWorkOrder::getWorkChain, "WL");
        qw.orderByAsc(ApsWorkOrder::getApsOrderId);
        qw.orderByAsc(ApsWorkOrder::getPlanEndDateTime);
        qw.orderByDesc(ApsWorkOrder::getLevel);
        List<ApsWorkOrder> oldList = apsWorkOrderMapper.selectList(qw);

        if (CollUtil.isEmpty(oldList)) {
            return;
        }

        List<ApsWorkOrder> list = new ArrayList<>();
        int seq = 1;
        String pickCode = "";
        if (coverFlag == null || coverFlag == 0) {
            list = oldList.stream().filter(e -> !StringUtils.hasText(e.getPickCode()) || e.getPickSeq() == null).collect(Collectors.toList());
            ApsWorkOrder max = new ApsWorkOrder();
            if (oldList.stream().allMatch(e->e.getPickSeq()==null)) {
                seq = 1;
                pickCode = serialCodeUtils.pickWailing();
            } else {
                max = oldList.stream().filter(e->e.getPickSeq()!=null&&StringUtils.hasText(e.getPickCode())).max(Comparator.comparingInt(ApsWorkOrder::getPickSeq)).orElse(new ApsWorkOrder());
                seq = max.getPickSeq() != null ? max.getPickSeq() + 1 : 1;
                pickCode = StringUtils.hasText(max.getPickCode()) ? max.getPickCode() : serialCodeUtils.pickWailing();
            }
        } else {
            list = oldList;
            pickCode = serialCodeUtils.pickWailing();
        }
        Map<Integer, List<ApsWorkOrder>> apsWorkOrderMap = list.stream().collect(Collectors.groupingBy(ApsWorkOrder::getBomId, Collectors.toList()));

        Order order = orderMapper.selectById(id);

        List<Integer> apsOrderIdList = list.stream().map(ApsWorkOrder::getApsOrderId).distinct().collect(Collectors.toList());
        Collections.sort(apsOrderIdList);

        Map<Integer, Integer> param = new HashMap<>();
        for (Integer bomId : apsWorkOrderMap.keySet()) {
            param.put(bomId, seq);
            LambdaUpdateWrapper<ApsWorkOrder> uw = new LambdaUpdateWrapper<>();
            uw.eq(ApsWorkOrder::getOrderId, id);
            uw.eq(ApsWorkOrder::getBomId, bomId);
            if (coverFlag == null || coverFlag == 0) {
                uw.and(euw -> euw.isNull(ApsWorkOrder::getPickCode).or().isNull(ApsWorkOrder::getPickSeq));
            }
            uw.set(ApsWorkOrder::getPickCode, pickCode);
            uw.set(ApsWorkOrder::getPickSeq, seq);
            apsWorkOrderMapper.update(null, uw);
            seq++;
        }

        List<OrderBom> orderBomList  = orderBomMapper.lambdaQuery().eq(OrderBom::getOrderId, id).list();
        Map<Integer, OrderBom> orderBomMap = orderBomList.stream().collect(Collectors.toMap(BaseEntity::getId, Function.identity()));

        List<WmsPartProcurementReqDto> wmsReqDto = new ArrayList<>();
        for (Integer bomId : apsWorkOrderMap.keySet()) {
            List<ApsWorkOrder> apsWorkOrderList = apsWorkOrderMap.get(bomId);
            if (CollUtil.isEmpty(apsWorkOrderList)) {
                continue;
            }
            ApsWorkOrder apsWorkOrder = apsWorkOrderList.get(0);
            if (!StringUtils.hasText(apsWorkOrder.getPlmId())) {
                continue;
            }
            WmsPartProcurementReqDto w = new WmsPartProcurementReqDto();
            // 物料类型
            w.setPickListNo(pickCode);
            w.setPickListItemNo(param.get(bomId));
            w.setMaterialCode(apsWorkOrder.getPlmId());
            w.setGrade(apsWorkOrder.getStandards());
            w.setMaterial(apsWorkOrder.getTexture());
            w.setItemNo(apsWorkOrder.getErpCode());
            w.setItemName(apsWorkOrder.getMaterName());
            w.setQty(apsWorkOrderList.stream().map(ApsWorkOrder::getOrderCount).reduce(BigDecimal.ZERO, BigDecimal::add).intValue());
            w.setPlanPickTime(apsWorkOrder.getPlanStartDateTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            w.setTimeStamp(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            w.setNextWorkPlace(apsWorkOrder.getWorkChain());
            w.setConstructOrderNo(apsWorkOrder.getWorkOrderCode());

            if (apsWorkOrder.getBomPid() != null){
                OrderBom orderBom = orderBomMap.get(apsWorkOrder.getBomPid());
                w.setRootPlmid(orderBom.getPlmId());
                w.setRootName(orderBom.getMaterName());
            }

            w.setWpxNo(null);

            w.setConstructNo(order.getConstructNo());
            apsWorkOrder.setPickCode(w.getPickListNo());

            wmsReqDto.add(w);
        }

        String url = "/mesApply/pickingApplyInAps";
        LogApi logApi = logApiUtils.getSendLog("mom-sy-solid-wms", "下发外购件领料单", url);
        logApiUtils.setReq(logApi, wmsReqDto);
        logApi.setQueryParam(id.toString());

        try {
            List<MesPicking> pickings = new ArrayList<>();
            for (WmsPartProcurementReqDto wgMaterialPickDto : wmsReqDto) {
                MesPicking picking = new MesPicking();
                picking.setPickListNo(Long.valueOf(wgMaterialPickDto.getPickListNo()));
                picking.setPickListItemNo(wgMaterialPickDto.getPickListItemNo());
                picking.setMaterialType(wgMaterialPickDto.getMaterialType());
                picking.setMaterialCode(wgMaterialPickDto.getMaterialCode());
                picking.setGrade(wgMaterialPickDto.getGrade());
                picking.setMaterial(wgMaterialPickDto.getMaterial());
                picking.setItemNo(wgMaterialPickDto.getItemNo());
                picking.setItemName(wgMaterialPickDto.getItemName());
                picking.setQty(wgMaterialPickDto.getQty());
                picking.setNextWorkPlace(wgMaterialPickDto.getNextWorkPlace());
                picking.setConstructNo(wgMaterialPickDto.getConstructNo());
                picking.setConstructOrderNo(wgMaterialPickDto.getConstructOrderNo());
                picking.setPlanPickTime(wgMaterialPickDto.getPlanPickTime());
                picking.setTimeStamp(wgMaterialPickDto.getTimeStamp());
                picking.setWpxNo(wgMaterialPickDto.getWpxNo());
                picking.setRootPlmid(wgMaterialPickDto.getRootPlmid());
                picking.setRootName(wgMaterialPickDto.getRootName());
                picking.setTarget("APS");
                pickings.add(picking);
            }

            Result result = wmsLtkApiClient.pickingApplyInAps(pickings);

            if (result.getCode() == 0) {
                String remark = "外购件领料单：" + pickCode;
                logApiUtils.successAndSave(logApi, result, remark);
            } else {
                logApiUtils.errorAndSave(logApi, result, result.getMessage());
            }
        } catch (Exception e) {
            logApiUtils.errorAndSave(logApi, "", e.getMessage());
            log.info("WMS-外购件领料单-错误{}：{}", id, e.getMessage());
        }

    }

    @SneakyThrows
    public String wlPartOutNew(String strXml) {
        XmlMapper xmlMapper = new XmlMapper();
        xmlMapper.enable(SerializationFeature.INDENT_OUTPUT);
        xmlMapper.configure(ToXmlGenerator.Feature.WRITE_XML_DECLARATION, true);

        MesResponse mesResponse = JacksonTool.xml2Java(strXml, MesResponse.class);

        List<PickingItemReq> data = mesResponse.getData();
        List<WmsPartOutboundReqDto> collect = data.stream()
                .map(e -> {
                    WmsPartOutboundReqDto dto = new WmsPartOutboundReqDto();
                    dto.setPickListNo(e.getPickListNo());
                    dto.setPickListItemNo(e.getPicklistLine().getPickListItemNo());
                    dto.setMaterialCode(e.getPicklistLine().getMaterialCode());
                    dto.setQty(e.getPicklistLine().getQty());
                    return dto;
                })
                .collect(Collectors.toList());

        MesXmlResult mesXmlResult = new MesXmlResult();
        mesXmlResult.setMsgSeqNo(mesResponse.getMsgSeqNo());
        try {
            partOutbound(collect);

            mesXmlResult.setStatusCode("200");
            mesXmlResult.setExpectCompletionMsg("Successful!");
            mesXmlResult.setErrorMessage("OK");
        } catch (Exception e) {
            mesXmlResult.setStatusCode("500");
            mesXmlResult.setExpectCompletionMsg(e.getMessage());
            mesXmlResult.setErrorMessage("ERROR");
        }

        String java2Xml = JacksonTool.java2Xml(mesXmlResult);
        return java2Xml;

    }

    @Transactional
    public void partOutbound(List<WmsPartOutboundReqDto> reqVo) {

        for (WmsPartOutboundReqDto wmsPartOutboundReqDto : reqVo) {
            List<ApsWorkOrder> list = apsWorkOrderMapper.lambdaQuery()
                    .eq(ApsWorkOrder::getWorkChain, WorkshopProp.WL_PHASE_CODE)
                    .eq(ApsWorkOrder::getPickCode, wmsPartOutboundReqDto.getPickListNo().toString())
                    .eq(ApsWorkOrder::getPickSeq, wmsPartOutboundReqDto.getPickListItemNo())
                    .in(ApsWorkOrder::getStatus, 2, 3)
                    .orderByAsc(ApsWorkOrder::getApsOrderId)
                    .orderByAsc(ApsWorkOrder::getPlanStartDateTime)
                    .list();

            int qty = wmsPartOutboundReqDto.getQty();

            for (ApsWorkOrder apsWorkOrder : list) {
                int ct = apsWorkOrder.getOrderCount().subtract(apsWorkOrder.getFinishCount()).intValue();
                if (ct >= qty) {
                    apsWorkOrder.setFinishCount(apsWorkOrder.getFinishCount().add(new BigDecimal(qty)));
                    if(apsWorkOrder.getFinishCount().compareTo(apsWorkOrder.getOrderCount()) >=0){
                        apsWorkOrder.setStatus(4);
                        apsWorkOrder.setActualEndDateTime(LocalDateTime.now());
                    }else{
                        apsWorkOrder.setStatus(3);
                    }
                    qty = 0;
                    apsWorkOrderMapper.updateById(apsWorkOrder);
                    break;
                }
                apsWorkOrder.setStatus(4);
                apsWorkOrder.setFinishCount(apsWorkOrder.getOrderCount());
                qty = qty - ct;
                apsWorkOrder.setActualStartDateTime(LocalDateTime.now());
                apsWorkOrder.setActualEndDateTime(LocalDateTime.now());
                apsWorkOrderMapper.updateById(apsWorkOrder);
            }
            String constructNo="";
            if(!CollectionUtils.isEmpty(list)){
                Order one = orderMapper.lambdaQuery().eq(Order::getId, list.get(0).getOrderId()).one();
                constructNo=one.getConstructNo();
            }

            partUtilService.addPartWl(constructNo,wmsPartOutboundReqDto.getMaterialCode(), wmsPartOutboundReqDto.getQty());

        }

    }

    @Transactional
    public void powderOutReceiveAps(Integer id) {
        QueryWrapper<OrderAccessories> qw = new QueryWrapper<>();
        qw.eq("oa.order_id", id);
        qw.likeRight("oa.mater_code", "050");
        qw.notLike("oa.mater_name", "漆");
        List<PowderOutReceiveApsReqVo> list = orderAccessoriesMapper.powderOutReceiveAps(qw);

        if (CollUtil.isEmpty(list)) {
            return ;
        }

        /*list.forEach(e->{
            e.setPowderType(e.getMaterCode().startsWith("0503")?"国产粉末底面合一涂料":"进口粉末底面合一涂料");
            e.setPerQuota(e.getSumQuota().divide(BigDecimal.valueOf(e.getRequireCount()), 4, RoundingMode.HALF_UP));
        });*/
        String pickCode = serialCodeUtils.pickPowder();
        int pickSeq = 1;
        for (PowderOutReceiveApsReqVo vo : list) {
            vo.setPowderType(vo.getMaterCode().startsWith("0503")?"国产粉末底面合一涂料":"进口粉末底面合一涂料");
            vo.setPerQuota(vo.getSumQuota().divide(BigDecimal.valueOf(vo.getRequireCount()), 4, RoundingMode.HALF_UP));
            vo.setPickCode(pickCode);
            vo.setPickSeq(pickSeq++);
        }

        String url = "/powderOut/powderOutReceiveAps";
        LogApi logApi = logApiUtils.getSendLog("mom-app-wms-bjk", "下发粉末定额领料单", url);
        logApiUtils.setReq(logApi, list);
        logApi.setQueryParam(id.toString());

        try {
            log.info("推送备件库粉末定额——请求：{}", JsonUtils.toJsonString(list));
            Result result = wmsBjkApiClient.powderOutReceiveAps(list);
            log.info("推送备件库粉末定额——响应：{}", JsonUtils.toJsonString(result));

            if (result.getCode() == 0) {
                String remark = "粉末领料单：" + pickCode;
                logApiUtils.successAndSave(logApi, result, remark);

                // 记录粉末定额领料单
                List<ApsAccessoryPick> collect = list.stream().map(e -> {
                    ApsAccessoryPick entity = new ApsAccessoryPick();
                    entity.setConstructCode(e.getConstructCode());
                    entity.setOrderId(id);
                    entity.setWorkOrderCode(e.getWorkOrderCode());
                    entity.setPickCode(e.getPickCode());
                    entity.setPickSeq(e.getPickSeq());
                    entity.setOrderQty(e.getRequireCount());
                    entity.setPickQty(0);
                    entity.setStockCode(null);
                    entity.setPickStatus(0);
                    return entity;
                }).collect(Collectors.toList());
                apsAccessoryPickMapper.insertBatchSomeColumn(collect);

            } else {
                logApiUtils.errorAndSave(logApi, result, result.getMessage());
            }
        } catch (Exception e) {
            logApiUtils.errorAndSave(logApi, "", e.getMessage());
            log.info("推送备件库粉末定额——错误{}：{}", id, e.getMessage());
        }

    }

    @Transactional
    public void powderOutDelete(BaseIdReqVo reqVo) {
        List<ApsAccessoryPick> list = apsAccessoryPickMapper.lambdaQuery()
                .eq(ApsAccessoryPick::getOrderId, reqVo.getId())
                .list();
        if (CollUtil.isEmpty(list)) {
            throw SyExceptionUtils.e("未查询到订单的粉末定额领料单");
        }
        if (list.stream().anyMatch(e -> e.getPickQty() != 0)) {
            throw SyExceptionUtils.e("该订单粉末有领料数据。");
        }
        List<PowderOutReceiveApsReqVo> collect = list.stream().map(e -> {
            PowderOutReceiveApsReqVo vo = new PowderOutReceiveApsReqVo();
            vo.setPickCode(e.getPickCode());
            vo.setPickSeq(e.getPickSeq());
            return vo;
        }).collect(Collectors.toList());
        Result result = wmsBjkApiClient.powderOutDelete(collect);
        if (result.getCode() != 0) {
            throw SyExceptionUtils.e(result.getMessage());
        }
        for (ApsAccessoryPick pick : list) {
            pick.setPickStatus(3);
            apsAccessoryPickMapper.updateById(pick);
        }
    }

    @Transactional
    public void powderOutNoticeAps(List<PowderOutNoticeApsReqVo> reqVo) {
        for (PowderOutNoticeApsReqVo vo : reqVo) {
            ApsAccessoryPick quota = apsAccessoryPickMapper.lambdaQuery()
                    .eq(ApsAccessoryPick::getPickCode, vo.getPickCode())
                    .eq(ApsAccessoryPick::getPickSeq, vo.getPickSeq())
                    .eq(ApsAccessoryPick::getWorkOrderCode, vo.getWorkOrderCode())
                    .one();
            if (ObjectUtils.isEmpty(quota)) {
                continue;
            }
            quota.setPickQty(quota.getPickQty() + vo.getPickQty());
            quota.setStockCode(vo.getStockCode());
            if (Objects.equals(quota.getPickQty(), quota.getOrderQty())) {
                quota.setPickStatus(2);
            } else {
                quota.setPickStatus(1);
            }
            apsAccessoryPickMapper.updateById(quota);
        }
    }

}
